﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Tb.App.API.Applications.Command.Basic;
using Tb.App.Domain.Rabbit.Basic;
using Tb.App.ErrorCode;
using Tb.App.Infrastructure.Interfaces;

namespace Tb.App.API.Applications.CommandHandler.Basic
{
    /// <summary>
    /// 修改溯源商品基本信息-命令
    /// </summary>
    public class UpdBasicCommandHandler : IRequestHandler<UpdBasicCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<BasicModel> basicRep;
        private readonly IMapper mapper;

        public UpdBasicCommandHandler(IBaseRepository<BasicModel> basicRep,IMapper mapper)
        {
            this.basicRep = basicRep;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(UpdBasicCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result=new ApiResult<int>();

            //批次唯一
            var count = await basicRep.GetAll().CountAsync(x => x.Batch == request.Batch&&!x.IsDel&&x.Id!=request.Id);
            if (count > 0) 
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnum.修改失败,
                    Message = "已存在同批次数据,请更新最新数据!!!",
                    Data = -1
                };
            }
            //var basic = await basicRep.GetAll().FirstOrDefaultAsync(x => !x.IsDel && x.Id == request.Id);
            //if (basic == null)
            //{
            //    return new ApiResult<int>()
            //    {
            //        Code = ApiEnum.修改失败,
            //        Message = "未找到该编号!!!",
            //        Data = -2
            //    };
            //}
            // 更新基础信息
            //mapper.Map(request, basic);
            //注释代码:查id修改的话,直接转换,否则会EF Core 的 DbContext 跟踪机制冲突

            //!
            //修改

            var entity =mapper.Map<BasicModel>(request);
            //entity.Updator=request.Updator;
            entity.UpdatorDate=DateTime.Now;
            var res= await basicRep.UpdateAsync(entity);
            if(res>0)
            {
                result.Code=ApiEnum.修改成功;
                result.Message=ApiEnum.修改成功.ToString();
                result.Data = res;
            }
            else
            {
                result.Code = ApiEnum.修改失败;
                result.Message = ApiEnum.修改失败.ToString();
                result.Data = res;
            }

            return await Task.FromResult(result);
        }
    }
}
